<?php

namespace App\Http\Controllers\group;

use App\Constant\Enum;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserWalletActive;
use App\Models\UserWithdraw;

class SummaryController extends BaseController
{
    public function preview()
    {
        /** @var User $user */
        $user = auth('jwt')->user();
        $exchangeRate = Setting::get('exchange_rate');
        // 总收入
        $total = UserWalletActive::query()
            ->where([
                'user_id' => $user->getAttribute('id'),
                'action' => Enum::WALLET_ACTIVE_ACTION_INCOME,
                'wallet_type' => Enum::WALLET_TYPE_COMMISSION,
                'status' => Enum::ADREWARD_DETAIL_COLLECT_STATUS_APPROVED,
            ])
            ->sum('coins');
        $total = sprintf("%.2f", $total / $exchangeRate);

        // 可提现金额
        $wallet = $user->wallet()->first();
        $withdrawable = sprintf("%.2f", (max(($wallet->commission_coins ?? 0), 0) - $wallet->locked_coins) / $exchangeRate);

        // 待审核金额
        $pending = UserWithdraw::query()
            ->where([
                'user_id' => $user->getAttribute('id'),
                'status' => Enum::TRANSACTION_STATUS_PENDING,
                'wallet_type' => Enum::WALLET_TYPE_COMMISSION,
            ])
            ->sum('money');

        // 已提现金额
        $coins = UserWalletActive::query()
            ->where([
                'user_id' => $user->getAttribute('id'),
                'action' => Enum::WALLET_ACTIVE_ACTION_OUTCOME,
                'wallet_type' => Enum::WALLET_TYPE_COMMISSION,
                'status' => Enum::ADREWARD_DETAIL_COLLECT_STATUS_APPROVED,
            ])
            ->sum('coins');
        $outcomes = sprintf("%.2f", $coins / $exchangeRate);

        return $this->success([
            'total' => $total,
            'withdrawable' => $withdrawable,
            'pending' => $pending,
            'outcomes' => $outcomes,
        ]);
    }
}
